package com.ctyon.watchmanager.ui.fragment;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CompoundButton;

import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.databinding.FragmentWatchBinding;
import com.ctyon.watchmanager.dialog.EditDialog;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.WatchInfoPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.orhanobut.logger.Logger;

import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class WatchFragment extends BaseFragment {

    public static final String TAG = "WatchFragment";

    private FragmentWatchBinding mBinding;
    private boolean mLowBatConfig;
    private int scene;
    private int lan;
    private String language;
    private EditDialog notifyDialog;

    public static WatchFragment newInstance() {
        final WatchFragment fragment = new WatchFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_watch, container, false);
        mBinding.setWatchPresenter(watchInfoPresenter);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mBinding.setWatch(BasicApp.getInstance().getWatch());

        mLowBatConfig = BasicApp.getInstance().getWatch().getLowBatConfig() == 1;

//        scene = BasicApp.getInstance().getWatch().getScene();
//        mBinding.spinnerWatchScene.setSelection(scene);
//        mBinding.spinnerWatchScene.setOnItemSelectedListener(sceneItemSelectedListener);

//        language = BasicApp.getInstance().getWatch().getLanguage();
//        if (DataUtil.isEmptyAnd(language) || !language.contains("*")){
//            lan = 1;
//        } else {
//            lan = Integer.parseInt(language.split("\\*")[0]);
//        }
//        mBinding.spinnerWatchLanguage.setSelection(lan);
//        mBinding.spinnerWatchLanguage.setOnItemSelectedListener(languageItemSelectedListener);

//        mBinding.setNotify(DataUtil.isEmptyOr(BasicApp.getInstance().getWatch().getNotify())?"":DataUtil.unicode2String(BasicApp.getInstance().getWatch().getNotify()));

    }

    private final WatchInfoPresenter watchInfoPresenter = new WatchInfoPresenter() {

        @Override
        public void onSosCheckedChanged(CompoundButton button, boolean checked) {
            Logger.t(LTAG).i("onSosCheckedChanged ： " + checked);
            if (mLowBatConfig == checked) {
                return;
            }
            NetService.getInstance()
                    .lowBatConfig(BasicApp.getInstance().getManager().getManagerId(),
                            BasicApp.getInstance().getWatch().getMeid(),
                            checked)
                    .timeout(10, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponseEntity>() {
                        @Override
                        public void onSuccess(BaseResponseEntity responseEntity) {
                            Logger.d("onSuccess : " + responseEntity.toString());
                            TSnackbarUtil.TSBSuccess(getActivity(), checked ? "开启成功" : "关闭成功");
                            mLowBatConfig = checked;
                            BasicApp.getInstance().getWatch().setLowBatConfig((byte) (mLowBatConfig ? 1 : 0));
                            mBinding.setWatch(BasicApp.getInstance().getWatch());
                        }

                        @Override
                        public void onErrorE(Throwable e) {
                            TSnackbarUtil.TSBSuccess(getActivity(), checked ? "开启失败" : "关闭失败");
                        }
                    });
        }

        @Override
        public void onNotifyClick(String notify) {
            Logger.t(LTAG).i("onNotifyClick");
            showNotifyDialog();
        }

    };

    private final AdapterView.OnItemSelectedListener sceneItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position != scene){
                final String method = "scene";
                if (NetService.getInstance().isDisable(method)) {
                    TSnackbarUtil.TSBError(getActivity(), "请稍候...");
                    return;
                }
                NetService.getInstance()
                        .method(method)
                        .scene(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), position)
                        .timeout(10, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<BaseResponseEntity>() {
                            @Override
                            public void onSuccess(BaseResponseEntity responseEntity) {
                                Logger.d("onSuccess : " + responseEntity.toString());
                                TSnackbarUtil.TSBSuccess(getActivity(), "设置成功");
                                scene = position;
                                BasicApp.getInstance().getWatch().setScene((byte) scene);
                            }

                            @Override
                            public String onOver() {
                                return method;
                            }
                        });

            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    private final AdapterView.OnItemSelectedListener languageItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position != lan){
                final String method = "language";
                if (NetService.getInstance().isDisable(method)) {
                    TSnackbarUtil.TSBError(getActivity(), "请稍候...");
                    return;
                }
                NetService.getInstance()
                        .method(method)
                        .language(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), position, getTimezone(position))
                        .timeout(10, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<BaseResponseEntity>() {
                            @Override
                            public void onSuccess(BaseResponseEntity responseEntity) {
                                Logger.d("onSuccess : " + responseEntity.toString());
                                TSnackbarUtil.TSBSuccess(getActivity(), "设置成功");
                                lan = position;
                                BasicApp.getInstance().getWatch().setLanguage(lan + "*" + getTimezone(lan));
                            }

                            @Override
                            public String onOver() {
                                return method;
                            }
                        });

            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    
    private final EditDialog.EditDialogCallback editDialogCallback = notify -> {
        if (DataUtil.isEmptyAnd(notify)){
            notify = "";
        } else {
            notify = notify.replace(" ", "").trim();
        }
        if (DataUtil.validateLegalString(notify)){
            TSnackbarUtil.TSBError(getActivity(), "内容包含非法字符");
            return;
        }
        if (notify.length() > 15){
            TSnackbarUtil.TSBError(getActivity(), "内容过长");
            return;
        }
        final String method = "notify";
        if (NetService.getInstance().isDisable(method)) {
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        String finalNotify = DataUtil.string2Unicode(notify);
        NetService.getInstance()
                .method(method)
                .notify(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), notify)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "设置成功");
                        BasicApp.getInstance().getWatch().setNotify(finalNotify);
                        mBinding.setNotify(DataUtil.isEmptyOr(finalNotify)?"":DataUtil.unicode2String(finalNotify));
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }
                });
    };

    private int getTimezone(int position){
        if (position == 0){
            return -4;
        } else if (position == 2){
            return 9;
        }
        return 8;
    }
    
    private void showNotifyDialog() {
        if (null == notifyDialog) {
            Logger.t(LTAG).i("Create Dialog");
            notifyDialog = new EditDialog(getActivity(), R.style.CustomDialog);
            notifyDialog.setEditCallback(editDialogCallback);
            notifyDialog.setCancelable(false);
            notifyDialog.setTitle("提示语");
            notifyDialog.setText(BasicApp.getInstance().getWatch().getNotify());
            notifyDialog.setHint("输入提示语,最多10字");
            Window window = notifyDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setWindowAnimations(R.style.CustomDialogStyle);
        }
        notifyDialog.show();
    }
    

}
